﻿using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Mvc.XForms.UI;
using Xunit;

namespace Mvc.XForms.Tests {
	public class When_serializing_for_WCF {
		private readonly XmlNamespaceManager nsmanager;

		public When_serializing_for_WCF() {
			nsmanager = new XmlNamespaceManager(new NameTable());
			nsmanager.AddNamespace("default", "http://schemas.datacontract.org/2004/07/Mvc.XForms.UI");
			nsmanager.AddNamespace("a", "http://schemas.datacontract.org/2004/07/Mvc.XForms.Tests");
		}

		[Fact]
		public void can_serialize_test_model_as_grid_items() {
			// Arrange
			var results = new LinqPagedSortedList<TestModel>(TestModel.AsQueryable(), 1, 5, "Name", SortDirection.Ascending);

			// Act
			var xdoc = Serialize(results);

			// Assert
			AssertXPath(xdoc, "//a:Name[1]", "Name1");
		}

		[Fact]
		public void can_serialize_LinqPagedList() {
			// Arrange
			var model = TestModel.AsQueryable();
			var results = new LinqPagedList<TestModel>(model, 1, 5);

			// Act
			var xdoc = Serialize(results);
		}

		[Fact]
		public void can_serialize_LinqSortedList() {
			// Arrange
			var model = TestModel.AsQueryable();
			var results = new LinqSortedList<TestModel>(model, "Name", SortDirection.Descending);

			// Act
			var xdoc = Serialize(results);
		}

		[Fact]
		public void can_serialize_LinqPagedSortedList() {
			// Arrange
			var model = TestModel.AsQueryable();
			var results = new LinqPagedSortedList<TestModel>(model, 1, 3, "Name", SortDirection.Descending);

			// Act
			var xdoc = Serialize(results);

			// Assert
			AssertXPath(xdoc, "//default:TotalCount", "5");
		}

		private void AssertXPath(XDocument xdoc, string xpath, string value) {
			var element = xdoc.XPathSelectElement(xpath, nsmanager);
			Assert.NotNull(element);
			Assert.Equal(value, element.Value);
		}

		private static XDocument Serialize<T>(T obj) {
			var ser = WcfSerializationHelper.Serialize(obj);
			ser = ser.TrimEnd('\0');
			var xdoc = XDocument.Parse(ser);

			return xdoc;
		}
	}
}
